package com.example.question.list.list1;

/**
 * @Date 2023-07-06
 * @Author Jonathan
 * @link {<a href="https://leetcode.cn/problems/split-linked-list-in-parts/">...</a>}
 */
public class Code14_725 {
    public static void main(String[] args) {
        ListNode listNode = List.createList(new int[]{1, 2, 3});
        Code14_725 code = new Code14_725();
        ListNode[] listNodes = code.splitListToParts(null, 5);
        System.out.println(listNodes);
    }

    public ListNode[] splitListToParts(ListNode head, int k) {
//        if (head == null) {
//            return null;
//        }

        int length = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            length++;
        }

        int count = length / k;
        int mod = length % k;
        ListNode[] ret = new ListNode[k];
        cur = head;
        for (int i = 0; i < k; i++) {
            int num = count;
            if (i < mod) {
                num = count + 1;
            }
            if (num > 0) {
                ListNode node = cur;
                ret[i] = node;
                cur = cur.next;
                for (int index = 1; index < num; index++) {
                    node.next = cur;
                    cur = cur.next;
                    node = node.next;
                }
                node.next = null;
            } else {
                ret[i] = null;
            }
        }
        return ret;
    }
}
